﻿using System;
using System.Configuration;
using StackExchange.Redis;

namespace Qy.Yzrb.Helpers
{
    public static class RedisHelper
    {
        private static ConnectionMultiplexer _redis;
        private static readonly Object Locker = new object();

        public static ConnectionMultiplexer Manager
        {
            get
            {
                if (_redis == null)
                {
                    lock (Locker)
                    {
                        if (_redis != null) return _redis;

                        _redis = GetManager();
                        return _redis;
                    }
                }

                return _redis;
            }
        }

        private static ConnectionMultiplexer GetManager(string connectionString = null)
        {
            if (string.IsNullOrEmpty(connectionString))
            {
                connectionString = GetDefaultConnectionString();
            }

            return ConnectionMultiplexer.Connect(connectionString);
        }

        private static string GetDefaultConnectionString()
        {
            return ConfigurationManager.AppSettings["redisConnectString"];
        }

        public static bool Remove(string key)
        {
            var db = Manager.GetDatabase();

            return db.KeyDelete(key);
        }

        public static string Get(string key)
        {
            var db = Manager.GetDatabase();

            return db.StringGet(key);
        }

        public static bool Set(string key, string value, int expireMinutes = 0)
        {
            var db = Manager.GetDatabase();

            if (expireMinutes > 0)
            {
                db.StringSet(key, value, TimeSpan.FromMinutes(expireMinutes));
            }
            else
            {
                db.StringSet(key, value);
            }

            return db.StringSet(key, value);
        }

        public static bool HasKey(string key)
        {
            var db = Manager.GetDatabase();

            return db.KeyExists(key);
        }
    }
}